package com.singletonapps.evory.service.impl;


import java.util.Date;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.singletonapps.evory.dao.RoleDao;
import com.singletonapps.evory.dao.UserDao;
import com.singletonapps.evory.dao.UserRoleDao;
import com.singletonapps.evory.dto.ResponseDto;
import com.singletonapps.evory.dto.UserDto;
import com.singletonapps.evory.entities.Role;
import com.singletonapps.evory.entities.User;
import com.singletonapps.evory.exception.UserAlreadyExistException;
import com.singletonapps.evory.service.UserService;
import com.singletonapps.evory.utils.SystemConstants;

@Service
public class UserServiceImpl implements UserService {
	
	private static final Logger LOGGER = LogManager.getLogger(UserServiceImpl.class.getName());
	
	@Autowired
	private UserDao userDao;
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private UserRoleDao userRoleDao;
	
	@Override
	@Transactional(rollbackFor = UserAlreadyExistException.class)
	public ResponseDto registerUser(UserDto userDto) throws UserAlreadyExistException{
		
		ResponseDto respuesta = new ResponseDto();
		
		try{
			
			User u = new User();
			u.setFirstName(userDto.getNombre());
			u.setLastName(userDto.getApellido());
			u.setEmail(userDto.getEmail());
			u.setUserName(userDto.getUsuario());
			u.setPassword(userDto.getPassword());
			u.setDateCreated(new Date());
		    u.setStatus(SystemConstants.USER_STATUS_ACTIVE);
		    
		    Role role = roleDao.getRole(SystemConstants.ROLE_USER);
		    u.getRole().add(role);
		    
			userDao.create(u);
			
			
			respuesta.setValid(true);
			
		}catch(DataIntegrityViolationException | ConstraintViolationException  e){
			LOGGER.error("Error creando el usuario", e);
			
			if(e instanceof ConstraintViolationException){
				if(e.getCause().getMessage().contains("UQ_USER_USER_EMAIL")){
					throw new UserAlreadyExistException(String.format("El email '%s' ya se encuentra registrado.", userDto.getEmail()));
				}
				if(e.getCause().getMessage().contains("UQ_USER_USER_LOGIN_NAME")){
					throw new UserAlreadyExistException(String.format("El nombre de usuario '%s'  ya se encuentra registrado.", userDto.getUsuario()));
				}
			}
		}catch (Exception e) {
			LOGGER.error("Error creando el usuario", e);
			throw new RuntimeException();
		}
		
		return respuesta;
	}

}
